import { Config, Context } from '../core';
import { Plugin } from '../core/plugin';
import { ScriptPlugin } from '../plugins/script';
import { CssPlugin } from '../plugins/css';
import { ResolveType, buildModuleGraph } from './build';
import { AssetsPlugin } from '../plugins/assets';
import { CopyPlugin } from '../plugins/copy';
import { generate } from './generate';

export * from './build';

export class Compiler {
  context: Context;

  constructor(config: Config) {
    const plugins: Plugin[] = [
      new ScriptPlugin(),
      new CssPlugin(),
      new AssetsPlugin(),
      new CopyPlugin(),
    ];
    this.context = new Context(config, plugins);
  }

  async compile() {
    // build 的作用: 生成 moduleGraph
    this.#build();
    // generate: 根据 moduleGraph 生成最后的文件
    await this.#generate();
  }

  #build() {
    buildModuleGraph(this.context, {
      // src/index.ts
      source: this.context.config.entry,
      importer: undefined,
      type: ResolveType.Entry,
    });
  }

  async #generate() {
    await generate(this.context);
  }
}
